package org.hotswap.agent.plugin.spring.getbean.cglib;
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

import org.hotswap.agent.plugin.spring.getbean.SpringHotswapAgentProxy;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.Factory;
import org.springframework.objenesis.SpringObjenesis;

public class HotswapAgentSpringBeanProxyCreator {

    public HotswapAgentSpringBeanProxyCreator() {
    }

    public static Object create(Object beanFactory, Object bean, Class[] classes, Object[] params) {
        HotswapSpringCallback callback = new HotswapSpringCallback(bean, beanFactory, classes, params);
        Enhancer enhancer = new Enhancer();
        enhancer.setUseCache(false);
        Class[] proxyInterfaces = new Class[bean.getClass().getInterfaces().length + 1];
        Class[] classInterfaces = bean.getClass().getInterfaces();

        for (int i = 0; i < classInterfaces.length; ++i) {
            proxyInterfaces[i] = classInterfaces[i];
        }

        proxyInterfaces[proxyInterfaces.length - 1] = SpringHotswapAgentProxy.class;

        enhancer.setInterfaces(proxyInterfaces);

        enhancer.setSuperclass(bean.getClass().getSuperclass());

        enhancer.setNamingPolicy(new HotswapAgentSpringNamingPolicy());

        enhancer.setCallbackType(HotswapSpringCallback.class);


        SpringObjenesis objenesis = new SpringObjenesis();
        if (objenesis.isWorthTrying()) {
            Class proxyClass = enhancer.createClass();
            Object proxyInstance = objenesis.newInstance(proxyClass, false);
            ((Factory) proxyInstance).setCallbacks(new Callback[]{callback});
            return proxyInstance;
        } else {
            enhancer.setCallback(callback);
            return enhancer.create();
        }
    }
}

